<template>
  <div class="search">
    <!-- 搜索组件一级路由   $router.back()返回上一个页面-->
    <van-nav-bar
      left-arrow
      title="搜索中心"
      @click-left="$router.back()"
    />

    <!-- https://youzan.github.io/vant/#/zh-CN/search -->
    <van-search
      v-model.trim="keyword"
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      @input="getSuggestions"
    >
      <template #action>
        <div @click="clickBtn">搜索</div>
      </template>
    </van-search>

    <!-- 联想建议 -->
    <van-cell-group v-if="keyword">
      <van-cell
        v-for="(item,index) in handleList"
        :key="item"
        icon="search"
        @click="clickSuggest(index)"
      >
        <div v-html="item" />
      </van-cell>
    </van-cell-group>
    <!-- /联想建议 -->

    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录" />
      <van-cell
        v-for="(item,index) in history"
        :key="item"
        :title="item"
        @click="clickHistory(item)"
      >
        <van-icon name="close" @click.stop="delHistory(index)" />
      </van-cell>
    </van-cell-group>

    <!-- /搜索历史记录 -->
  </div>
</template>

<script>
import { reqGetSuggestions } from '@/api/search'
import { setHistory, getHistory } from '@/utils/storage'
export default {
  name: 'Search',
  data() {
    return {
      keyword: '', // 搜索关键字
      list: [], // 联想建议结果
      history: getHistory(),
      timeId: null
    }
  },
  computed: {
    handleList() {
      /* const reg = new RegExp(this.keyword, 'gi')
          const res = this.list.map(item => {
          return item.replace(reg, (val) => {
            return `<span style="color: red">${val}</span>`
          })
        })
      return res */
      return this.list.map(item => item.replace(new RegExp(this.keyword, 'gi'), (val) => `<span style="color: red">${val}</span>`))
    }
  },
  methods: {
    // 获取联想建议
    getSuggestions() {
      clearTimeout(this.timeId)
      if (this.keyword.length === 0) {
        // 清空数据
        this.list = []
        return
      }
      this.timeId = setTimeout(async() => {
        const { data: { data: { options }}} = await reqGetSuggestions(this.keyword)
        this.list = options
      }, 500)
      // 可以实现展示但是会影响后续功能
      /*  const reg = new RegExp(this.keyword, 'gi')
      const res = options.map(item => {
        return item.replace(reg, (val) => {
          return `<span style="color: red">${val}</span>`
        })
      })
      console.log(res) */
    },
    // 点击搜索按钮
    clickBtn() {
      this.addHistory(this.keyword)
    },
    // 点击的搜索建议
    clickSuggest(index) {
      this.addHistory(this.list[index])
    },
    // 点击历史记录
    clickHistory(item) {
      this.addHistory(item)
    },
    // 添加历史的方法
    addHistory(value) {
      this.history.unshift(value)
      // 历史唯一
      // const res = new Set(this.history)
      // console.log([...res])
      this.history = [...new Set(this.history)]
      // localStorage.setItem('history', JSON.stringify(this.history))
      setHistory(this.history)
      // 页面跳转
      // this.$router.push(`/searchResult?keyword=${value}`)
      this.$router.push({
        path: '/searchResult',
        query: {
          keyword: value
        }
      })
    },
    // 删除历史
    delHistory(index) {
      // 截取下标
      this.history.splice(index, 1)
      // localStorage.setItem('history', JSON.stringify(this.history))
      setHistory(this.history)
    }
  }

}
</script>

<style lang="" scoped>

</style>
